package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import butterknife.BindView;
import com.bugtags.library.Bugtags;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.AppManager;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SimpleWebViewParams;
import com.isunland.managesystem.entity.SysDistrict;
import com.isunland.managesystem.entity.SysDistrictListOriginal;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.CheckLineView;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/5/18 14:32
 */
@SuppressWarnings("unused") public class TestFragment extends BaseFragment {
  private static final int RREQUEST_PROJECT_TYPE = 1;
  private static final int RREQUEST_DEPT_TYPE = 2;
  private static final int RREQUEST_REGION_TYPE = 3;
  private static final int REQUEST_LAUNCH_ACTIVITY = 4;
  private static final int REQUEST_CHANGE_PATH = 5;
  private static final int REQUEST_LAUNCH_FUNCTION = 6;
  @BindView(R.id.slv_projectType_test) SingleLineView slvProjectTypeTest;
  @BindView(R.id.slv_dept_test) SingleLineView slvDeptTest;
  @BindView(R.id.slv_region_test) SingleLineView slvRegionTest;
  @BindView(R.id.slv_batch_over) SingleLineView slvBatchOver;
  @BindView(R.id.slv_path_test) SingleLineView slvPath;
  @BindView(R.id.clv_isBugtags) CheckLineView clvIsBugtags;
  @BindView(R.id.clv_isLog) CheckLineView clvIsLog;
  @BindView(R.id.clv_isPush) CheckLineView clvIsPush;
  @BindView(R.id.clv_isMock) CheckLineView clvIsMock;
  @BindView(R.id.slv_launch_test) SingleLineView slvLaunch;
  @BindView(R.id.slv_function_test) SingleLineView slvFunction;
  @BindView(R.id.slv_restart_test) SingleLineView slvRestart;
  @BindView(R.id.slv_account_test) SingleLineView slvAccount;
  @BindView(R.id.slv_signOut_test) SingleLineView slvSignOut;
  @BindView(R.id.slv_web_test) SingleLineView slvWeb;
  @BindView(R.id.slv_handWriting_test) SingleLineView slvHandWriting;

  @Override protected int initLayoutId() {
    return R.layout.fragment_test;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(R.string.devOption);
    slvLaunch.setTextContent(
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_LAUNCH_ACTIVITY, ""));
    slvFunction.setTextContent(
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_LAUNCH_NAME, ""));

    slvProjectTypeTest.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        testProjectKind();
      }
    });
    slvDeptTest.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        testDeptKind();
      }
    });
    slvRegionTest.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        testRegionKind();
      }
    });
    slvBatchOver.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new BatchOverDialog(), 0);
      }
    });
    slvPath.setTextContent(ApiConst.getUrlMain());
    slvPath.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new NetWorkSettingDialogFragment(), REQUEST_CHANGE_PATH);
      }
    });
    slvAccount.setTextContent(mCurrentUser.getName());
    slvAccount.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //切换账号.
        showDialogNames(MyUtils.getUserNames());
      }
    });
    slvLaunch.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //showDialog(new SelectActivityDialogFragment(), REQUEST_LAUNCH_ACTIVITY);
        BaseVolleyActivity.newInstance(TestFragment.this, SelectLaunchActivity.class, null,
            REQUEST_LAUNCH_ACTIVITY);
      }
    });
    slvFunction.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        BaseVolleyActivity.newInstance(TestFragment.this, FunctionSearchListActivity.class, null,
            REQUEST_LAUNCH_FUNCTION);
      }
    });
    slvRestart.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        reStart();
      }
    });
    clvIsBugtags.getCbCheck().setChecked(MyUtils.isBugTags(mActivity));
    clvIsBugtags.getCbCheck()
        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
              SharedPreferencesUtil.setBoolean(mActivity, SharedPreferencesUtil.KEY_IS_BUGTAGS,
                  true);
              SharedPreferencesUtil.setInt(getActivity(), SharedPreferencesUtil.BUGTAGS_OPTIONS,
                  Bugtags.BTGInvocationEventBubble);
              Bugtags.setInvocationEvent(Bugtags.BTGInvocationEventBubble);
              ToastUtil.show("您已开启测试人员选项(悬浮球)");
              LogUtil.i("test=", "testCompileTime");
            } else {
              SharedPreferencesUtil.setBoolean(mActivity, SharedPreferencesUtil.KEY_IS_BUGTAGS,
                  false);
              SharedPreferencesUtil.setInt(getActivity(), SharedPreferencesUtil.BUGTAGS_OPTIONS,
                  Bugtags.BTGInvocationEventNone);
              Bugtags.setInvocationEvent(Bugtags.BTGInvocationEventNone);
              ToastUtil.show("您已关闭测试人员选项");
            }
          }
        });
    clvIsLog.getCbCheck().setChecked(MyUtils.isLog(mActivity));
    clvIsLog.getCbCheck().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        SharedPreferencesUtil.setBoolean(mActivity, SharedPreferencesUtil.KEY_IS_LOG, isChecked);
      }
    });
    clvIsPush.getCbCheck().setChecked(MyUtils.isPush(mActivity));
    clvIsPush.getCbCheck().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        SharedPreferencesUtil.setBoolean(mActivity, SharedPreferencesUtil.KEY_IS_PUSH, isChecked);
      }
    });
    clvIsMock.getCbCheck().setChecked(MyUtils.isMock());
    clvIsMock.getCbCheck().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        SharedPreferencesUtil.setBoolean(mActivity, SharedPreferencesUtil.KEY_IS_MOCK, isChecked);
      }
    });
    slvSignOut.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        AppManager.getAppManager().finishAllActivity();
        //退出登陆时不清空用户名和密码,下次显示登陆页面回填用户名和密码.
        mCurrentUser.setLogin(false);
        startActivity(new Intent(mActivity, LoginActivity.class));
      }
    });
    slvWeb.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        BaseVolleyActivity.newInstance(TestFragment.this, SimpleWebViewActivity.class,
            new SimpleWebViewParams().setTitle("视频播放")
                .setUrl(ApiConst.getAbsoluteUrl(ApiConst.URL_WEIJIA_INTRODUCTION))
                .setLoadUrl(true)
                .setShowLoadingDialog(true), 0);
      }
    });
    slvHandWriting.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        BaseVolleyActivity.newInstance(TestFragment.this, HandWritingTestActivity.class, null, 0);
      }
    });
  }

  /** 测试项目类别 */
  private void testProjectKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    //noinspection unchecked
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("选择项目类型");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_PROJECT_TYPE_TREE);
    params.setSelectType(SimpleTreeListParams.ONLY_CHILD);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dictFlag", "projectKindCode")
            .put("type", "mobile"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, RREQUEST_PROJECT_TYPE);
  }

  /** 测试项目类别 */
  private void testRegionKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    params.setItem(new SysDistrict("中国", "100"));
    params.setChildField("code");
    params.setParentField("pcode");
    params.setTitleField("districtName");
    params.setTitle("选择地址");
    params.setClassOriginal(SysDistrictListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_ADDRESS);
    params.setParamsNotEmpty(new ParamsNotEmpty().put("pcode", "").put("memberCode", ""));
    BaseVolleyActivity.newInstance(this, AddressTreeListActivity.class, params,
        RREQUEST_REGION_TYPE);
  }

  private void testDeptKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("北京信普达系统工程有限公司");
    item.setId("100014");
    //noinspection unchecked
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setContentField("extParam2");
    params.setTitle("选择部门");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_DEPT_TREE);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("type", "mobile"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, RREQUEST_DEPT_TYPE);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == RREQUEST_PROJECT_TYPE) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      slvProjectTypeTest.setTextContent(params.getFullName());
    }
    if (requestCode == RREQUEST_DEPT_TYPE) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      slvDeptTest.setTextContent(item.getName());
    }
    if (requestCode == RREQUEST_REGION_TYPE) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      SysDistrict item = ((SysDistrict) params.getItem());
      slvRegionTest.setTextContent(item.getDistrictName());
    }
    if (requestCode == REQUEST_LAUNCH_ACTIVITY) {
      BaseParams params = (BaseParams) data.getSerializableExtra(EXTRA_PARAMS);
      slvLaunch.setTextContent(params.getTitle());
    }
    if (requestCode == REQUEST_LAUNCH_FUNCTION) {
      BaseParams params = (BaseParams) data.getSerializableExtra(EXTRA_PARAMS);
      slvFunction.setTextContent(params.getTitle());
    }
    if (requestCode == REQUEST_CHANGE_PATH) {
      slvPath.setTextContent(ApiConst.getUrlMain());
    }
  }

  private void reStart() {
    AppManager.getAppManager().finishAllActivity();
    startActivity(new Intent(mActivity, SplashActivity.class));
  }

  private void showDialogNames(final LinkedHashMap<String, String> map) {
    if (map == null || map.size() == 0) return;
    ArrayList<String> nameArr = new ArrayList<>(map.keySet());
    Collections.sort(nameArr, new Comparator<String>() {
      public int compare(String mapping1, String mapping2) {
        return mapping1.compareTo(mapping2);
      }
    });
    AlertDialog.Builder builderSingle = new AlertDialog.Builder(mActivity);
    //builderSingle.setIcon(R.drawable.ic_launcher);
    builderSingle.setTitle("Select One Name:");

    final ArrayAdapter<String> arrayAdapter =
        new ArrayAdapter<>(mActivity, android.R.layout.select_dialog_singlechoice);
    arrayAdapter.addAll(nameArr);
    builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });

    builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {
        String strName = arrayAdapter.getItem(which);
        //LogUtil.i("mEtUsername=" + strName + ",pwd=" + mNameMap.get(strName));
        mCurrentUser.setName(strName);
        mCurrentUser.setPassword(map.get(strName));
        slvAccount.setTextContent(strName);
      }
    });
    builderSingle.show();
  }
}
